<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2023-10-12 18:08:47
 * @LastEditors: 甯左龙 1173405584@qq.com
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\form\uiInput\uiInput.vue
 * CIMC-V2
-->
<template>
  <UiFormItem :class="{ hidden: info.extension.hidden.value || conditionProperty.hidden }" :info="info">
    <div class="w-full">
      <el-input
        :ref="info._id"
        v-model="formDataModel"
        v-ui-ref="vSetRef"
        :autosize="{ minRows: 2, maxRows: 4 }"
        :class="[
          { hasPrefix: info.extension.prefixIcon && info.extension.prefixIcon.value },
          info.extension.fontWeight && info.extension.fontWeight.value,
          { hasTextColor: info.extension.textColor && info.extension.textColor.value },
        ]"
        clearable
        :disabled="info.extension.disabled.value || conditionProperty.disabled"
        :placeholder="info.extension.placeholder.value"
        :size="info.extension.size.value"
        :style="[{ fontSize: fontSize }]"
        :type="info.extension.type.value"
        @change="handleChange"
        @input="handleInput"
        @keyup.control="handleCtrl"
        @keyup.enter="$handleEnter"
      >
        <!-- 后置图标 -->
        <template #suffix>
          <vui-icon v-if="info.extension.suffixIcon && info.extension.suffixIcon.value" :icon="info.extension.suffixIcon.value" />
        </template>
        <!-- 前置图标 -->
        <template #prefix>
          <vui-icon v-if="info.extension.prefixIcon && info.extension.prefixIcon.value" :icon="info.extension.prefixIcon.value" />
        </template>
        <!-- 前缀内容 -->
        <template #prepend v-if="showPrepend">
          <span v-if="getPrepend.type === 'text'">{{ getPrepend.defaultValue }}</span>
          <el-select
            v-else-if="getPrepend.type === 'select'"
            v-model="prependModel"
            class="w-[70px]"
            :disabled="info.extension.disabled.value || conditionProperty.disabled"
            filterable
            :size="info.extension.size ? info.extension.size.value : 'mini'"
            @change="setExpendFormData('prepend')"
          >
            <el-option
              v-for="item in prependOptions"
              :key="`${item[getPrepend.valueField]}`"
              :label="item[getPrepend.labelField]"
              :value="item[getPrepend.valueField]"
            >
              <span>{{ item[getPrepend.labelField] }}</span>
            </el-option>
          </el-select>
          <el-radio-group
            v-else-if="getPrepend.type === 'radio'"
            v-model="prependModel"
            :disabled="info.extension.disabled.value || conditionProperty.disabled"
            :size="info.extension.size ? info.extension.size.value : 'mini'"
            @change="setExpendFormData('prepend')"
          >
            <el-radio-button v-for="item in prependOptions" :key="`${item[getPrepend.valueField]}`" :label="item[getPrepend.valueField]">
              {{ item[getPrepend.labelField] }}
            </el-radio-button>
          </el-radio-group>
        </template>
        <!-- 后缀内容 -->
        <template #append v-if="showAppend">
          <span v-if="getAppend.type === 'text'">{{ getAppend.defaultValue }}</span>
          <el-select
            v-else-if="getAppend.type === 'select'"
            v-model="appendModel"
            class="w-[70px]"
            :disabled="info.extension.disabled.value || conditionProperty.disabled"
            filterable
            :size="info.extension.size ? info.extension.size.value : 'mini'"
            @change="setExpendFormData('append')"
          >
            <el-option
              v-for="item in appendOptions"
              :key="`${item[getAppend.valueField]}`"
              :label="item[getAppend.labelField] || 'label'"
              :value="item[getAppend.valueField] || 'value'"
            >
              <span>{{ item[getAppend.labelField] }}</span>
            </el-option>
          </el-select>
          <el-radio-group
            v-else-if="getAppend.type === 'radio'"
            v-model="appendModel"
            :disabled="info.extension.disabled.value || conditionProperty.disabled"
            :size="info.extension.size ? info.extension.size.value : 'mini'"
            @change="setExpendFormData('append')"
          >
            <el-radio-button v-for="item in appendOptions" :key="`${item[getAppend.valueField]}`" :label="item[getAppend.valueField]">
              {{ item[getAppend.labelField] }}
            </el-radio-button>
          </el-radio-group>
        </template>
      </el-input>
    </div>
  </UiFormItem>
  <!-- 预设内容 -->
  <div v-if="info.extension.presetText && info.extension.presetText.options && info.extension.presetText.value" id="preset">
    <el-button v-for="item in info.extension.presetText.options" v-show="item.value !== ''" :key="item" @click.stop="presetClick(item.value)">
      {{ item.value }}
    </el-button>
  </div>
</template>
<script>
  import { defineComponent } from 'vue'
  import { UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin } from '@ve/mixin'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import { processingConstant, replaseRegVariable } from '@ve/utils/utils'
  import merge from 'lodash/merge'
  import isEmpty from 'lodash/isEmpty'
  import isArray from 'lodash/isArray'

  export default defineComponent({
    name: 'UiInput',
    components: {},
    mixins: [UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin],
    data() {
      return {
        prependOptions: [],
        appendOptions: [],
        prependModel: '',
        appendModel: '',
      }
    },
    computed: {
      textColor() {
        return this.info.extension.textColor?.value ? this.info.extension.textColor.value : ''
      },
      bgColor() {
        return this.info.extension.bgColor?.value ? this.info.extension.bgColor.value : ''
      },
      fontSize() {
        return this.info.extension.fontSize?.value ? this.info.extension.fontSize.value : ''
      },
      placeholderColor() {
        return this.info.extension.placeholderColor_v1?.value ? this.info.extension.placeholderColor_v1.value : ''
      },
      getPrepend() {
        let prependConfig = {}
        if (this.info.extension.prepend) {
          if (this.info.extension.prepend.type === 'exInput') {
            prependConfig = {
              type: 'text',
              defaultValue: this.info.extension.prepend.value,
            }
          } else {
            prependConfig = this.info.extension.prepend.value
            this.prependOptions = this.info.extension.prepend.value.optionConfig
          }
        }
        return prependConfig
      },
      getAppend() {
        let appendConfig = {}
        if (this.info.extension.append) {
          if (this.info.extension.append.type === 'exInput') {
            appendConfig = {
              type: 'text',
              defaultValue: this.info.extension.append.value,
            }
          } else {
            appendConfig = this.info.extension.append.value
            this.prependOptions = this.info.extension.append.value.optionConfig
          }
        }
        return appendConfig
      },
      showAppend() {
        let show = false
        if (this.info.extension.append && this.info.extension.append.value) {
          show = true
          if (this.info.extension.append.value.type === 'text' && !this.info.extension.append.value.defaultValue) {
            // 如果为新版扩展配置并且文本类型无值时不显示
            show = false
          }
        }
        return show
      },
      showPrepend() {
        let show = false
        if (this.info.extension.prepend && this.info.extension.prepend.value) {
          show = true
          if (this.info.extension.prepend.value.type === 'text' && !this.info.extension.prepend.value.defaultValue) {
            // 如果为新版扩展配置并且文本类型无值时不显示
            show = false
          }
        }
        return show
      },
    },
    watch: {
      formDataModel: {
        deep: true,
        handler(newval) {
          if (!newval && newval !== 0) return
          // if (this.info.extension.type.value == 'textarea') {
          //   this.formDataModel = newval.split('\r\n')[0].split('\n').join(',')
          // } else {
          this.formDataModel = String(newval)
          // }
        },
      },
    },
    created() {
      // 设置前后置扩展值
      if (this.getPrepend.type !== 'text' && this.getPrepend.Model) {
        setTimeout(() => {
          this.getFormData(true)[this.getPrepend.Model] = this.getPrepend.defaultValue
        })
      }
      if (this.getAppend.type !== 'text' && this.getAppend.Model) {
        setTimeout(() => {
          this.getFormData(true)[this.getAppend.Model] = this.getAppend.defaultValue
        })
      }
    },
    methods: {
      handleCtrl(val) {
        if (
          val.key == 'Control' &&
          val.target.value &&
          val.target.value.indexOf('\n') &&
          this.info.extension.type.value == 'textarea' &&
          this.info.extension.isCopyComma?.value
        ) {
          let txtVal = val.target.value
          let txtList = txtVal.split('\n')
          if (!txtList[txtList.length - 1]) {
            txtList.splice(txtList.length - 1, 1)
          }
          this.formDataModel = txtList.join(',')
        }
      },
      handleInput() {
        this.setPageModulesState('value', this.formDataModel)
      },
      handleChange() {
        // 调用 change 事件
        this.onChange()
        this.formDataModel = this.formDataModel.trim()
      },
      presetClick(val) {
        this.formDataModel = this.formDataModel + val
      },
      setExpendFormData(expendType) {
        if (expendType === 'prepend' && this.getPrepend.Model) {
          this.getFormData(true)[this.getPrepend.Model] = this.prependModel
        } else if (expendType === 'append' && this.getAppend.Model) {
          this.getFormData(true)[this.getAppend.Model] = this.appendModel
        }
      },
      requestExpendData(cb) {
        if (this.getPrepend.api) {
          let requestDataObj = {}
          this.getPrepend.requestData.forEach((item) => {
            let itemVal = item.value
            if (/#{.*?}/g.test(item.value)) {
              itemVal = replaseRegVariable(itemVal, this.getFormData(true))
            }
            requestDataObj[item.key] = processingConstant(this, itemVal)
          })
          let options = {
            api: this.getPrepend.api,
            method: this.getPrepend.method,
            getDataKey: this.getPrepend.getDataKey,
            data: merge(requestDataObj, this.getFormData(true)),
          }
          this.request(options, 'prepend')
        }
        if (this.getAppend.api) {
          let requestDataObj = {}
          this.getAppend.requestData.forEach((item) => {
            let itemVal = item.value
            if (/#{.*?}/g.test(item.value)) {
              itemVal = replaseRegVariable(itemVal, this.getFormData(true))
            }
            requestDataObj[item.key] = processingConstant(this, itemVal)
          })
          let options = {
            api: this.getAppend.api,
            method: this.getAppend.method,
            getDataKey: this.getAppend.getDataKey,
            data: merge(requestDataObj, this.getFormData(true)),
          }
          this.request(options, 'append')
        }
        cb && cb()
      },
      request(options = {}, type) {
        let getDataKey = options.getDataKey
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(options.data),
            method: options.method,
          },
        }).then((res) => {
          let optionList = isEmpty(getDataKey) ? res.data.data || [] : res.data[getDataKey].data || []
          if (isArray(optionList)) {
            if (type === 'prepend') {
              this.prependOptions = optionList
            } else if (type === 'append') {
              this.appendOptions = optionList
            }
          } else {
            if (type === 'prepend') {
              this.prependOptions = []
            } else if (type === 'append') {
              this.appendOptions = []
            }
          }
        })
      },
    },
  })
</script>
<style scoped>
  :deep() .hasPrefix .el-input__inner {
    padding-left: 25px;
  }
  :deep(.hasTextColor) .el-textarea__inner,
  :deep(.hasTextColor) .el-input__inner {
    color: v-bind(textColor);
  }
  :deep() .el-input.is-disabled .el-input__inner,
  :deep() .el-input__inner {
    background-color: v-bind(bgColor);
  }
  :deep() input.el-input__inner:-moz-placeholder {
    color: v-bind(placeholderColor);
  }

  :deep() input.el-input__inner::-moz-placeholder {
    color: v-bind(placeholderColor);
  }

  :deep() input.el-input__inner:-ms-input-placeholder {
    color: v-bind(placeholderColor);
  }
  #preset {
    margin: 2px;
    padding: 5px;
    display: inline-block;
    width: 100%;
    text-align: end;
  }

  :deep() input.el-input__inner::-webkit-input-placeholder {
    color: v-bind(placeholderColor);
  }

  :deep() .el-radio-group .el-radio-button .el-radio-button__inner {
    height: 24px;
    border-top: none;
  }

  :deep() .el-input-group__append,
  :deep() .el-input-group__prepend {
    padding: 0 8px;
  }

  :deep() .el-input-group__prepend .el-select {
    margin: -10px -8px;
  }
</style>
